package com.hawthorn.redis.service.division.impl;

import com.hawthorn.component.constant.RedisConstant;
import com.hawthorn.component.utils.common.StrMyUtil;
import com.hawthorn.entity.dto.SysDivisionDTO;
import com.hawthorn.platform.redis.RedisMyClient;
import com.hawthorn.platform.utils.common.MyUtil;
import com.hawthorn.redis.repository.DivisionCacheMapper;
import com.hawthorn.redis.service.division.DivisionCacheService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>todo 加载行政区划缓存服务实现类 </p>
 * @author: andyten@tom.com | xukaixing@hotmail.com
 * @created: 2022/06/30 12:32 PM
 * @version v1.0.2
 * @copyright: Copyright (c)  andyten
 */
@Service
@Slf4j
public class DivisionCacheServiceImpl implements DivisionCacheService
{
  @Resource
  RedisMyClient redisMyClient;

  @Resource
  private DivisionCacheMapper divisionCacheMapper;

  @Transactional(readOnly = true)
  public void init()
  {
    List<SysDivisionDTO> divisionCache = divisionCacheMapper.selectDivision();
    String key;
    // todo 先删除redis中的key
    redisMyClient.removeAll(StrMyUtil.placeHolder(RedisConstant.REDIS_KEY_DIVISION_PREFIX, "*"));

    for (SysDivisionDTO sysDivisionDTO : divisionCache)
    {
      key = StrMyUtil.placeHolder(RedisConstant.REDIS_KEY_DIVISION_PREFIX, sysDivisionDTO.getCode());

      redisMyClient.hSet(key, RedisConstant.REDIS_KEY_DIVISION_CODE, sysDivisionDTO.getCode());
      redisMyClient.hSet(key, RedisConstant.REDIS_KEY_DIVISION_DNAME, sysDivisionDTO.getDname());
      redisMyClient.hSet(key, RedisConstant.REDIS_KEY_DIVISION_SNAME, sysDivisionDTO.getSname());
      redisMyClient.hSet(key, RedisConstant.REDIS_KEY_DIVISION_TYPE, MyUtil.getValue(sysDivisionDTO.getType()));
      redisMyClient.hSet(key, RedisConstant.REDIS_KEY_DIVISION_PARENT, MyUtil.getValue(sysDivisionDTO.getParent()));
    }

    log.info("====== load division data to redis success ======");
  }
}
